package dhm.com.hpx.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dhm.com.hpx.R;
import dhm.com.hpx.activity.CollectionActivity;
import dhm.com.hpx.activity.CouponActivity;
import dhm.com.hpx.activity.ExportActivity;
import dhm.com.hpx.activity.ExtensionActivity;
import dhm.com.hpx.activity.FansActivity;
import dhm.com.hpx.activity.FeedbackActivity;
import dhm.com.hpx.activity.LikeActivity;
import dhm.com.hpx.activity.LoginActivity;
import dhm.com.hpx.activity.MainActivity;
import dhm.com.hpx.activity.ManagerActivity;
import dhm.com.hpx.activity.MemberActivity;
import dhm.com.hpx.activity.MinecardActivity;
import dhm.com.hpx.activity.MyorderActivity;
import dhm.com.hpx.activity.MyrecommendActivity;
import dhm.com.hpx.activity.PdfActivity;
import dhm.com.hpx.activity.SettingActivity;
import dhm.com.hpx.activity.SpeechcraftActivity;
import dhm.com.hpx.activity.UserActivity;
import dhm.com.hpx.base.BaseFragment;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.utils.SpUtils;

public class MineFragment extends BaseFragment implements LoginContract.IView {
    Unbinder unbinder;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.gather)
    TextView gather;
    @BindView(R.id.fans)
    TextView fans;
    @BindView(R.id.follow)
    TextView follow;
    @BindView(R.id.collection)
    TextView collection;

    private PressenterImpl pressenter;
    private String uid;

    @Override
    protected int getLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        uid = SpUtils.getString(getActivity(), "uid");
        initData();
    }

    @Override
    protected void initData() {
        showPopwindow();
        isLoad=false;
        uid = SpUtils.getString(getActivity(), "uid");
        if (uid == null || uid.equals("")) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            getActivity().startActivity(intent);
            getActivity().finish();
        }else {
            Map<String,String> map=new HashMap<>();
            map.put("token",Constant.TOKEN);
            map.put("uid",uid);
            pressenter.sendMessage(getActivity(),Constant.get_userinfo,map,GetUserInfoBean.class);
        }
    }


    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_mine, container, false);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfoBean) {
            GetUserInfoBean getUserInfoBean = (GetUserInfoBean) data;
            if (getUserInfoBean.getCode() == 1) {

                if (getUserInfoBean.getData().getMobile()==null||getUserInfoBean.getData().getMobile().equals("")){
                    SpUtils.saveString(getActivity(), "phone", getUserInfoBean.getData().getUser_login());
                }else {
                    SpUtils.saveString(getActivity(), "phone", getUserInfoBean.getData().getMobile());
                }
                image.setImageURI(Constant.PATH + "/" + getUserInfoBean.getData().getHeadsmall());
                nick.setText(getUserInfoBean.getData().getUser_nickname());
                gather.setText(getUserInfoBean.getData().getCollectionCount() + "");
                collection.setText(getUserInfoBean.getData().getFavoritesCount() + "");
                fans.setText(getUserInfoBean.getData().getFansnum()+"");
                follow.setText(getUserInfoBean.getData().getFollowCount()+"");
            }
        }
    }


    @Override
    public void fail(String error) {

    }

    @OnClick({R.id.setting,R.id.lin_fans,R.id.lin_dather,R.id.lin_follow,R.id.lin_collection, R.id.member, R.id.mycard, R.id.tui, R.id.share, R.id.dao, R.id.huashu, R.id.myorder, R.id.coupon, R.id.like, R.id.member_center, R.id.use, R.id.yijian, R.id.callus})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.setting:
                intent= new Intent(getActivity(), SettingActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.lin_fans:
                intent= new Intent(getActivity(), FansActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.member:
                intent= new Intent(getActivity(), MemberActivity.class);
                intent.putExtra("receive_id","0");
                getActivity().startActivity(intent);
                break;
            case R.id.mycard:
                intent= new Intent(getActivity(), MinecardActivity.class);
                intent.putExtra("uid",uid);
                getActivity().startActivity(intent);
                break;
            case R.id.lin_collection:
                intent=new Intent(getActivity(), CollectionActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.lin_follow:
                intent=new Intent(getActivity(), UserActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.lin_dather:
                intent=new Intent(getActivity(), ManagerActivity.class);
                intent.putExtra("type", "1");
                getActivity().startActivity(intent);
                break;
            case R.id.tui:
                intent=new Intent(getActivity(), ExtensionActivity.class);
                intent.putExtra("type","1");
                getActivity().startActivity(intent);
                break;
            case R.id.share:
                intent=new Intent(getActivity(), MyrecommendActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.dao:
                intent=new Intent(getActivity(), ExportActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.huashu:
                intent=new Intent(getActivity(), SpeechcraftActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.myorder:
                intent=new Intent(getActivity(), MyorderActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.coupon:
                intent=new Intent(getActivity(), CouponActivity.class);
                intent.putExtra("type","1");
                getActivity().startActivity(intent);
                break;
            case R.id.like:
                intent=new Intent(getActivity(), LikeActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.member_center:
                intent= new Intent(getActivity(), MemberActivity.class);
                intent.putExtra("receive_id","0");
                getActivity().startActivity(intent);
                break;
            case R.id.use:

                intent = new Intent(getActivity(), PdfActivity.class);
                getActivity().startActivity(intent);

                break;
            case R.id.yijian:
                intent=new Intent(getActivity(), FeedbackActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.callus:
               /* // 检查是否获得了权限（Android6.0运行时权限）
                //权限没有获得
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // 没有获得授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getActivity(),
                            Manifest.permission.CALL_PHONE)) {
                        // 返回值：
                        // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                        // 如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                        // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                        // 弹窗需要解释为何需要该权限，再次请求授权
                        Toast.makeText(getActivity(), "请授权拨打电话权限！", Toast.LENGTH_LONG).show();

                        // 帮跳转到该应用的设置界面，让用户手动授权
                        intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                        intent.setData(uri);
                        getActivity().startActivity(intent);
                    } else {
                        // 不需要解释为何需要该权限，直接请求授权
                        ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.CALL_PHONE}, 100);
                    }
                } else {
                    // 已经获得授权，可以打电话
                    CallPhone();
                }*/


                setBackgroundAlpha(0.5f);
                popWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
               
               
                break;
                default:
        }
    }

    private void CallPhone() {
        // 拨号：激活系统的拨号组件
        Intent intent = new Intent(); // 意图对象：动作 + 数据
        intent.setAction(Intent.ACTION_DIAL); // 设置动作
        Uri data = Uri.parse("tel:" + "17605081987"); // 设置数据
        intent.setData(data);
        getActivity().startActivity(intent); // 激活Activity组件
    }


    /**
     * 判断2个时间大小
     * yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     * @param startTime
     * @param endTime
     * @return
     */
    public static String timeCompare(String startTime, String endTime){
        int i=0;
    //注意：传过来的时间格式必须要和这里填入的时间格式相同
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime()<date1.getTime()){
                //结束时间小于开始时间
                i= 1;
            }else if (date2.getTime()==date1.getTime()){
                //开始时间与结束时间相同
                i= 2;
            }else if (date2.getTime()>date1.getTime()){
                //结束时间大于开始时间
            i= 3;
            }
        } catch (Exception e) {

        }

        return  i+"";
    }




    private PopupWindow popWindow;

    private void showPopwindow() {
        View popView = View.inflate(getActivity(), R.layout.dialog_exit, null);
        TextView title_ = popView.findViewById(R.id.title_);
        TextView title = popView.findViewById(R.id.title);
        TextView cancle = popView.findViewById(R.id.cancle);
        TextView sure = popView.findViewById(R.id.sure);

        title_.setText("联系方式");
        title.setText("QQ：166357914");
        sure.setText("复制");



        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", "166357914");
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                Toast.makeText(getActivity(), "复制成功", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();
            }
        });

        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }



}
